package com.one.common.common.login.presenter;

import android.content.Context;

import com.one.common.R;
import com.one.common.common.login.model.LoginModel;
import com.one.common.common.login.model.extra.WxExtra;
import com.one.common.common.login.view.SendCodeView;
import com.one.common.config.CMemoryData;
import com.one.common.config.CPersisData;
import com.one.common.config.RouterPath;
import com.one.common.manager.RouterManager;
import com.one.common.model.bean.UserInfoBean;
import com.one.common.model.http.callback.ObserverOnNextListener;
import com.one.common.model.http.callback.ObserverOnResultListener;
import com.one.common.presenter.BaseApiPresenter;
import com.one.common.utils.FieldCheckUtil;
import com.one.common.utils.Logger;
import com.one.common.utils.MyToast;
import com.one.common.utils.StringUtils;
import com.one.common.utils.Toaster;
import com.one.common.view.base.BaseActivity;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录
 */
public class LoginPresenter extends BaseApiPresenter<SendCodeView, LoginModel> {
    public LoginPresenter(SendCodeView mView, Context mContext) {
        super(mView, mContext, new LoginModel((BaseActivity) mContext));
    }

    /**
     * 注册，保存用户信息
     */
    public void register(String phone, String pwd, String type, String code, String pwdC) {
        if (checkDataAll(phone, pwd, code, pwdC)) {
            return;
        }
        mModel.register(getMap(phone, pwd, type, code), new ObserverOnResultListener<UserInfoBean>() {
            @Override
            public void onResult(UserInfoBean userInfoBean) {
                CMemoryData.setUserInfo(userInfoBean);
                if (mView != null) {
                    mView.finishPage();
                }
            }
        });
    }

    public void register(String phone, String pwd, String type, String code) {
        register(phone, pwd, type, code, "-1");
    }

    /**
     * 验证码
     */
    public void sendCode(String mobile, String type) {
        mModel.sendCode(mobile, type, new ObserverOnNextListener<String>() {
            @Override
            public void onNext(String s) {
                Toaster.showLongToast("发送成功\n请注意查收", MyToast.SUCCESS);
            }

            @Override
            public void onError(String errorCode, String msg) {
                Toaster.showLongToast(msg, MyToast.FAIL);
                mView.resetCountDown();
            }
        });
    }

    /**
     * 登录
     */
    public void login(String mobile, String pwd, String type) {
        if (checkDataLogin(mobile, pwd)) {
            return;
        }
        mModel.login(getMap(mobile, pwd, type), new ObserverOnResultListener<UserInfoBean>() {
            @Override
            public void onResult(UserInfoBean userInfoBean) {
                loginSuccess(userInfoBean);
            }
        });
    }

    /**
     * 登录成功
     */
    public void loginSuccess(UserInfoBean userInfoBean) {
        Toaster.showLongToast("登录成功", MyToast.SUCCESS);
        // 用户信息缓存本地 去主界面
        Logger.d("zlj", "login  " + userInfoBean.toString());
        CMemoryData.setUserInfo(userInfoBean);
        CPersisData.setIsLogin(true);
        if (mView != null) {
            mView.finishPage();
        }
        RouterManager.getInstance().goAndFinish(mActivity, RouterPath.MAIN_PAGE);
    }

    /**
     * 重置密码
     */
    public void resetPwd(String mobile, String pwd, String code, String pwds, String type) {
        if (checkDataAll(mobile, pwd, code) || checkDataNewPwd(pwd, pwds)) {
            return;
        }
        mModel.resetPwd(getMap(mobile, pwd, type, code), new ObserverOnResultListener<String>() {
            @Override
            public void onResult(String s) {
                Toaster.showLongToast("修改成功", MyToast.SUCCESS);
                if (mView != null)
                    mView.finishPage();
            }
        });
    }


    /**
     * 获取参数
     */
    private Map<String, String> getMap(String mobile, String pwd, String type, String code) {
        Map<String, String> params = new HashMap<>();
        params.put("member_account", mobile);
        params.put("member_password", pwd);
        if (StringUtils.isNotBlank(code)) {
            params.put("code", code);
        }
        params.put("member_type", type);// 1:普通用户 2:师傅
        return params;
    }

    private Map<String, String> getMap(String mobile, String pwd, String type) {
        return getMap(mobile, pwd, type, null);
    }

    /**
     * 验证参数 注册 忘记密码
     */
    private boolean checkDataAll(String mobile, String pwd, String code, String pwdC) {
        if (checkDataLogin(mobile, pwd)) {
            return true;
        } else if (StringUtils.isBlank(code)) {
            Toaster.showLongToast(StringUtils.format(R.string.toast_code_null), MyToast.FAIL);
            return true;
        } else if (!FieldCheckUtil.checkVerificationCode(code)) {
            Toaster.showLongToast(StringUtils.format(R.string.toast_code_error), MyToast.FAIL);
            return true;
        } else if (!FieldCheckUtil.checkPassword(pwd)) {
            Toaster.showLongToast(StringUtils.format(R.string.toast_pwd_error), MyToast.FAIL);
            return true;
        } else if (!pwdC.equals("-1") && !pwd.equals(pwdC)) {
            Toaster.showLongToast(StringUtils.format(R.string.toast_c_pwd_error), MyToast.FAIL);
            return true;
        }

        return false;
    }

    private boolean checkDataAll(String mobile, String pwd, String code) {
        return checkDataAll(mobile, pwd, code, "-1");
    }

    /**
     * 验证参数登录
     */
    private boolean checkDataLogin(String mobile, String pwd) {
        if (checkDataPhone(mobile)) {
            return true;
        } else if (StringUtils.isBlank(pwd)) {
            Toaster.showLongToast(StringUtils.format(R.string.toast_pwd_null), MyToast.FAIL);
            return true;
        }
        return false;
    }

    /**
     * 验证手机号
     */
    public boolean checkDataPhone(String mobile) {
        if (StringUtils.isBlank(mobile) || !FieldCheckUtil.checkPhoneNumber(mobile)) {
            Toaster.showLongToast(StringUtils.format(R.string.toast_phone_fial), MyToast.FAIL);
            return true;
        }
        return false;
    }

    /**
     * 验证手机号
     */
    private boolean checkDataNewPwd(String newPwd, String newPwds) {
        if (!newPwd.equals(newPwds)) {
            Toaster.showLongToast(StringUtils.format(R.string.toast_new_pwd_error), MyToast.FAIL);
            return true;
        }
        return false;
    }


    /**
     * 绑定手机号
     */
    public void bindPhone(String code, String phone, WxExtra extra) {
        if (StringUtils.isBlank(code)) {
            Toaster.showLongToast(StringUtils.format(R.string.toast_code_null), MyToast.FAIL);
            return;
        }
        if (checkDataPhone(phone)) {
            return;
        }
        Map<String, String> param = new HashMap<>();
        param.put("weixin_app_open_id", extra.getOpenId());
        param.put("member_account", phone);
        param.put("code", code);
        param.put("member_img", extra.getMember_img());
        param.put("member_nick_name", extra.getMember_nick_name());

        mModel.bindPhone(param, new ObserverOnResultListener<UserInfoBean>() {
            @Override
            public void onResult(UserInfoBean o) {
                loginSuccess(o);
            }
        });
    }


    /**
     * 微信登陆
     */
    public void wxLogin(final WxExtra extra) {
        mModel.wxLogin(extra.getOpenId(), new ObserverOnResultListener<UserInfoBean>() {
            @Override
            public void onResult(UserInfoBean userInfoBean) {
                if (userInfoBean.getMember_id().equals("0")) {
                    // 需要绑定手机号
                    RouterManager.getInstance().go(RouterPath.BIND_PHONE, extra);
                } else {
                    loginSuccess(userInfoBean);
                }
            }
        });
    }

}
